package com.longtop.leaning.dao;

import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordFilter;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

import com.longtop.leaning.entity.User;
import com.longtop.leaning.serializable.UserSerializable;
import com.longtop.leaning.util.StringUtils;

public class UserRMSDao implements UserDao{

	private static final UserRMSDao instance = new UserRMSDao();
	
	private UserRMSDao() {
	}
	
	public static UserRMSDao getInstance(){
		return instance;
	}

	public void test(){
		RecordStore rs;
		try {
			rs = RMSUtil.getUserRecordStore();
			
			
			System.out.println(rs.getNumRecords());
			
			User user = new UserRMSDao().getUser("11", "22");
			System.out.println(user);
			
			rs.closeRecordStore();
		} catch (RecordStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	public int addUser(User user) {
		RecordStore rs = RMSUtil.getUserRecordStore();
		int recordId = RMSUtil.addRecord(rs, UserSerializable.getInstance().serialize(user));
		System.out.println("rms store user: loginid "+ user.getLoginid() + ",pw "+user.getPasswd());
		RMSUtil.closeRecordStore(rs);
		return recordId;
	}
	
	public User getUser(String loginid, String passwd) {
		System.out.println("rms find user: loginid "+ loginid + ",pw "+passwd);
		User user = null;
		RecordStore rs = RMSUtil.getUserRecordStore();

		RecordEnumeration re = RMSUtil.enumerateRecords(rs, new UserFilter(loginid, passwd), null, false);
		if(re.numRecords() == 1){
			byte nextRec[] = RMSUtil.nextRecord(re);
			user = (User)UserSerializable.getInstance().deserialize(nextRec);
		}
		if(user == null){
			System.out.println("rms get user: null");
		}else{
			System.out.println("rms get user: loginid "+ user.getLoginid() + ",pw "+user.getPasswd());
		}
		return user;
	}
	
	public void clearUser() {
		RMSUtil.deleteRecordStore(RMSUtil.FLT_RMS_NAME);
	}

	class UserFilter implements RecordFilter {
		private String loginid = "";
		private String passwd = null;

		public UserFilter(String loginid, String passwd) {
			this.loginid = loginid;
			this.passwd = passwd;
		}

		public boolean matches(byte[] candidate) {
			if(StringUtils.isEmpty(loginid) || StringUtils.isEmpty(passwd)){
				return false;
			}
			User user = (User) UserSerializable.getInstance().deserialize(candidate);

			return user.getLoginid().equals(loginid.trim()) && user.getPasswd().equals(passwd.trim());
		}
	}
	
}
